import {Circle as CircleStyle, Fill, Stroke, Style, Text, Icon} from 'ol/style'
import {LineString, Point, Polygon} from 'ol/geom.js';
import Feature from 'ol/Feature.js';
import {Cluster, Vector as VectorSource, XYZ} from 'ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer.js';
import {createEmpty, extend, getHeight, getWidth} from 'ol/extent.js';

export default {
  data() {
    return {}
  },
  methods: {
    /**
     * 动态聚合
     * @param Features {Object:{}}
     * @param options {Object:{}}
     */
    dynamicCluster(Features, options) {
      const outerCircleFill = new Fill({
        color: 'rgba(255, 153, 102, 0.3)',
      });
      const innerCircleFill = new Fill({
        color: 'rgba(255, 165, 0, 0.7)',
      });
      const textFill = new Fill({
        color: '#fff',
      });
      const textStroke = new Stroke({
        color: 'rgba(0, 0, 0, 0.6)',
        width: 3,
      });
      const innerCircle = new CircleStyle({
        radius: 14,
        fill: innerCircleFill,
      });
      const outerCircle = new CircleStyle({
        radius: 20,
        fill: outerCircleFill,
      });

      const lightIcon = new Icon({
        src: this.$mapicon.alarmFenceMarkerIcon,
        anchor: [0.5, 0.5],
        anchorOrigin: 'bottom-right',
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        offsetOrigin: 'top-left',
        scale: 1,
        offset: [0, 0]
      });

      //
      function clusterMemberStyle(clusterMember) {
        let data = clusterMember.get('data')
        return new Style({
          geometry: clusterMember.getGeometry(),
          image: lightIcon,
          text: new Text({
            // text: data.name,
            // offsetY: -30,
            // font: 'bold 12px 宋体',
            // fill: new Fill({
            //   color: '#639575'
            // })
          }),
        });
      }

      const vectorSource = new VectorSource({
        features: Features
      });
      const clusterSource = new Cluster({
        attributions: '',
        distance: 35,
        source: vectorSource,
      });

      function clusterStyle(feature) {
        const size = feature.get('features').length;
        if (size > 1) {
          return [
            new Style({
              image: outerCircle,
            }),
            new Style({
              image: innerCircle,
              text: new Text({
                text: size.toString(),
                fill: textFill,
                stroke: textStroke,
              }),
            }),
          ];
        }
        const originalFeature = feature.get('features')[0];
        return clusterMemberStyle(originalFeature);
      }

      // Layer displaying the clusters and individual features.
      let code = options.code || 'dynamic-cluster-layer'
      const clusters = new VectorLayer({
        code: code,
        source: clusterSource,
        style: clusterStyle,
        zIndex: 102
      });

      // 把图层添加到地图
      this.map.addLayer(clusters)
      this.map.un('pointermove', pointermoveFun.bind(this))
      this.map.on('pointermove', pointermoveFun.bind(this));

      function pointermoveFun(event) {
        clusters.getFeatures(event.pixel).then((features) => {
          this.map.getTargetElement().style.cursor = features.length ? 'pointer' : '';
        });
      }

      // 双击放大
      this.map.un('dblclick', dblclickFun.bind(this))
      this.map.on('dblclick', dblclickFun.bind(this));

      function dblclickFun(event) {
        clusters.getFeatures(event.pixel).then((features) => {
          if (features.length > 0) {
            const clusterMembers = features[0].get('features');
            if (clusterMembers.length > 1) {
              // Calculate the extent of the cluster members.
              const extent = createEmpty();
              clusterMembers.forEach((feature) =>
                extend(extent, feature.getGeometry().getExtent())
              );
              const view = map.getView();
              const resolution = map.getView().getResolution();
              if (
                view.getZoom() === view.getMaxZoom() ||
                (getWidth(extent) < resolution && getHeight(extent) < resolution)
              ) {
                // Show an expanded view of the cluster members.

              } else {
                // Zoom to the extent of the cluster members.
                view.fit(extent, {duration: 500, padding: [200, 200, 200, 200]});
              }
            }
          }
        });
      }

      this.map.un('click', clickFun.bind(this))
      this.map.on('click', clickFun.bind(this));

      function clickFun(event) {
        clusters.getFeatures(event.pixel).then((features) => {
          if (features.length > 0) {
            const clusterMembers = features[0].get('features');
            if (clusterMembers.length === 1) {
              this.clusterFeatureClick(event, clusterMembers[0])
            } else if (clusterMembers.length > 1) {
              this.clusterFeaturesClick(event, clusterMembers)
            }
          }
        });
      }
    },
    // 点击单个要素
    clusterFeatureClick(e, Feature) {
      this.clickMapFeature && this.clickMapFeature(e, Feature)
    },
    // 点击簇要素
    clusterFeaturesClick(e, Features) {
      this.clickMapFeatures && this.clickMapFeatures(e, Feature)
    }
  }
}
